import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../config.dart';

class DioHttp {
  Dio? _client;
  late BuildContext context;

  DioHttp._internal(BuildContext context) {
    if (_client == null || context != this.context) {
      this.context = context;
      var options = BaseOptions(baseUrl: Config.baseUrl, connectTimeout: 1000 * 10, receiveTimeout: 1000 * 3, extra: {'context': context});
      var client = Dio(options);
      _client = client;
    }
  }

  //Get 请求
  Future<Response<Map<String, dynamic>>> get(String path, [Map<String, dynamic>? params, String? token]) async {
    var options = Options(headers: {'Authorization': token});
    return await _client!.get(path, queryParameters: params, options: options);
  }

  //Post 请求
  Future<Response<Map<String, dynamic>>> post(String path, [Map<String, dynamic>? params, String? token]) async {
    var options = Options(headers: {'Authorization': token});
    return await _client!.post(path, queryParameters: params, options: options);
  }

  //Post 请求(带参数)'multipart/form-data'
  Future<Response<Map<String, dynamic>>> postFormData(String path, [Map<String, dynamic>? params, String? token]) async {
    var options = Options(headers: {'Authorization': token}, responseType: ResponseType.plain);
    options.contentType = 'multipart/form-data';
    return await _client!.post(path, queryParameters: params, options: options);
  }

  static DioHttp of(BuildContext context) {
    return DioHttp._internal(context);
  }
}
